package com.cpi.basilos.stock.converter;

import org.apache.log4j.Logger;

import com.cpi.basilos.corntype.converter.CornTypeConverter;
import com.cpi.basilos.corntype.exception.CornTypeException;
import com.cpi.basilos.corntype.view.CornTypeView;
import com.cpi.basilos.stock.dto.StockDTO;
import com.cpi.basilos.stock.exception.StockException;
import com.cpi.basilos.stock.view.StockView;
import com.cs.common.utils.NumberUtil;

public class StockConverter {
	private static final String ERROR_SAP = "Error SAP";//$NON-NLS-1$
	private static org.apache.log4j.Logger logger = Logger.getLogger(StockConverter.class);
	public StockView convertDTOToView(StockDTO stockDTO)throws StockException{
		StockView stockView = null;
		CornTypeView cornTypeView = null;
		CornTypeConverter cornTypeConverter = null;
		try{
			cornTypeConverter = new CornTypeConverter();
			stockView = new StockView();
			cornTypeView = cornTypeConverter.convertDTOToView(stockDTO.getCornType());
			stockView.setCornTypeView(cornTypeView);
			stockView.setLocation(stockDTO.getLocation() != null ? Integer.parseInt(stockDTO.getLocation()) : 0);
			if( stockDTO.getSapAmount() == -1 ){
				stockView.setSapAmount(ERROR_SAP);
			}else{
				stockView.setSapAmount(NumberUtil.convertQuantity(stockDTO.getSapAmount()/1000) + " ton");
			}
			stockView.setCimaAmount(NumberUtil.convertQuantity(stockDTO.getAmount()));
			if(stockDTO.getSize()!=0){
				stockView.setPercentage((int)(stockDTO.getAmount()*100/stockDTO.getSize()));
			}else{
				stockView.setPercentage((int)(stockDTO.getAmount()*100/stockDTO.getAmount()));
			}
		}catch(Exception exception){
			StockException stockException = null;
			logger.error(exception);
			exception.printStackTrace(System.err);
			stockException = new StockException(exception,CornTypeException.LAYER_CONVERTER, CornTypeException.ACTION_SELECT);
			throw stockException;
		}
		return stockView;
	}
}